package com.onpositive.notes.android.ui.elements;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.onpositive.businessdroids.model.IColumn;
import com.onpositive.businessdroids.model.IField;
import com.onpositive.businessdroids.model.IModelChangeListener;
import com.onpositive.businessdroids.model.TableModel;
import com.onpositive.businessdroids.model.aggregation.IAggregator;
import com.onpositive.businessdroids.model.impl.AbstractCollectionBasedModel;
import com.onpositive.businessdroids.model.impl.AbstractComputableField;
import com.onpositive.businessdroids.model.impl.Column;
import com.onpositive.businessdroids.ui.IOpenListener;
import com.onpositive.businessdroids.ui.dataview.DataViewFactory;
import com.onpositive.businessdroids.ui.dataview.StructuredDataView;
import com.onpositive.collections.Delta;
import com.onpositive.collections.ICollectionDelta;
import com.onpositive.collections.IObjectCollection;
import com.onpositive.notes.android.main.CommonResources;
import com.onpositive.notes.android.main.EditNoteActivity;
import com.onpositive.notes.android.main.ViewDeltaActivity;
import com.onpositive.notes.model.INote;
import com.onpositive.notes.model.ITemplate;
import com.onpositive.notes.services.BasicCollectionRegistry;
import com.onpositive.notes.services.BasicNoteRegistry;

public class CollectionHistoryUI {
	
	public static final String EXTRA_KEY_DELTA = "delta";
	private StructuredDataView sdv;
	private IObjectCollection collection = null ;
	
	private Column dateField = new Column( new AbstractComputableField() {

		@Override
		public Object getPropertyValue(Object object) {

			if (object == null)
				return "NULL";

			if (object instanceof ICollectionDelta) {
				ICollectionDelta<?> delta = (ICollectionDelta<?>) object ;
				Date date = delta.getDate() ;
				SimpleDateFormat sdf =
						new SimpleDateFormat( "dd,MMMM,yyyy HH:mm", CommonResources.defaultLocale ) ;
				
				String result = sdf.format(date);
				return result;
			}
			return object.toString();
		}
	} );
	
	private Column templateField = new Column( new AbstractComputableField() {

		@Override
		public Object getPropertyValue(Object object) {

			if (object == null)
				return "NULL";

			if (object instanceof ICollectionDelta) {
				ICollectionDelta<?> delta = (ICollectionDelta<?>) object ;
				ITemplate template = delta.getTemplate();
				String result = template.getText();
				return result;
			}
			return object.toString();
		}
	} );
	
	public View createView( final Context context ){
		
		LinearLayout lt = new LinearLayout( context );
		lt.setOrientation( LinearLayout.VERTICAL ) ;
		
		while(true){
			if( !(context instanceof Activity) )
				break ;
			
			Bundle extras = ((Activity)context).getIntent().getExtras();
			if( extras == null )
				break ;
	        
			if( !extras.containsKey( UIConstants.EXTRA_KEY_COLLECTION ) )
				break ;
			
			Integer id = extras.getInt( UIConstants.EXTRA_KEY_COLLECTION ) ;
			if( id == null )
				break ;	
			
			collection = BasicCollectionRegistry.getInstance().getCollection(id) ;			
			break ;
		}
		if( collection == null )
			return lt ;


		
		IField[] fields = new IField[]{ templateField, dateField } ;
		
		sdv = DataViewFactory.createList(
				context, collection.getCompleteHistory(), null, null, fields);
		
		TextView titleView = new TextView( context);
		titleView.setText( collection.getName() ) ;
		lt.addView( titleView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT) ) ;
		
		sdv.setActionBarVisible(true) ;
		sdv.setHeaderVisible(true) ;
		sdv.setFooterVisible(true) ;

		
		sdv.setOpenListener(new IOpenListener() {

			@Override
			public void openElement(View parent, View elementView, Object element, int pos)
			{
				if(!(context instanceof Activity) )
					return ;
				
				Activity activity = (Activity) context ;
				
				ICollectionDelta<?> delta = (ICollectionDelta<?>) element;
				INote note = delta.getNote();
				Intent intent = new Intent( context, EditNoteActivity.class);
				intent.putExtra(UIConstants.EXTRA_KEY_NOTE, note);
				intent.putExtra(UIConstants.EXTRA_KEY_INDEX, pos);
				activity.startActivityForResult(intent, UIConstants.REQUEST_EDIT_NOTE);
			}
		});

		sdv.getTableModel().addModelChangeListener( new IModelChangeListener() {
			
			@Override
			public void aggregatorChanged(IAggregator oldAggregator,
					IAggregator newAggregator, IColumn column) {}
			
			@Override
			public void modelChanged(TableModel model) {
				
				HashSet<Integer> presentDelta = new HashSet<Integer>() ;
				HashSet<Integer> displayedDelta = new HashSet<Integer>() ;
				for( ICollectionDelta<?> delta : collection.getCompleteHistory() )
					presentDelta.add(delta.getId()) ;
				
				
				ArrayList<Object> toDelete = new ArrayList<Object>() ;
				final AbstractCollectionBasedModel tModel = (AbstractCollectionBasedModel)sdv.getTableModel();
				Collection<Object> content = tModel.getContent();
				for( Object obj : content ){
					ICollectionDelta<?> delta = (ICollectionDelta<?>) obj ;
					final int id = delta.getId();
					displayedDelta.add(id) ;
					if( !presentDelta.contains( id ) )
						toDelete.add(delta) ;
				}
				
				for( ICollectionDelta<?> delta : collection.getCompleteHistory() ){
					if(!displayedDelta.contains(delta.getId()))
						tModel.addItem(delta) ;					
				}
				
				for( Object obj : toDelete )
					tModel.removeItem(obj) ;
			}
		}) ;
		
		lt.addView(sdv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		return lt ;	
	}
	

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && requestCode == UIConstants.REQUEST_EDIT_NOTE) {
			
			if( sdv == null )
				return ;
			
			Bundle extras = data.getExtras();
			if(extras == null)
				return ;

			if (!data.hasExtra(UIConstants.EXTRA_KEY_NOTE))
				return;
			
			INote newNote = (INote) extras.get(UIConstants.EXTRA_KEY_NOTE);
			AbstractCollectionBasedModel tableModel = (AbstractCollectionBasedModel)sdv.getTableModel();

			if (data.hasExtra(UIConstants.EXTRA_KEY_INDEX)) {
				int ind = extras.getInt(UIConstants.EXTRA_KEY_INDEX);
				Delta<?> oldDelta = (Delta<?>) tableModel.getItem(ind);
				BasicNoteRegistry.getInstance().unRegisterNote( oldDelta.getNote() ) ;
			}
			boolean delete = false ;
			if( data.hasExtra("delete") ){
				delete = data.getBooleanExtra("delete", false) ;
			}
			if(!delete)
				BasicNoteRegistry.getInstance().registerNote(newNote) ;
			
			tableModel.fireModelChanged() ;
		}
	}

}
